package com.wkq.net.interceptor;


import com.wkq.net.util.NetworkUtil;
import com.wkq.net.util.SignUtil;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import okhttp3.CacheControl;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.GzipSource;


/**
 * 缓存拦截器
 */
public abstract class WBCacheInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        // 有网络时, 缓存10秒

        int maxAge = 10;


        if ("POST".equals(request.method())) {
            HttpUrl.Builder authorizedUrlBuilder = request.url().newBuilder();

            Map<String, String> parameter = new HashMap<>();

            for (String key : request.url().queryParameterNames()) {
                parameter.put(key, request.url().queryParameter(key));
                authorizedUrlBuilder.removeAllQueryParameters(key);
            }

            FormBody.Builder builder = new FormBody.Builder();

            for (Map.Entry<String, String> entity : SignUtil.getOpenSignMap(parameter).entrySet()) {
                builder.add(entity.getKey(), entity.getValue());
            }
            RequestBody newBody = builder.build();
             request = request.newBuilder()
                    .method(request.method(), newBody)
                    .url(authorizedUrlBuilder.build())
                    .build();

        } else {
            HttpUrl.Builder authorizedUrlBuilder = request.url().newBuilder();

            Map<String, String> parameter = new HashMap<>();

            for (String key : request.url().queryParameterNames()) {
                parameter.put(key, request.url().queryParameter(key));
                authorizedUrlBuilder.removeAllQueryParameters(key);
            }

            for (Map.Entry<String, String> entity : SignUtil.getOpenSignMap(parameter).entrySet()) {
                authorizedUrlBuilder.addQueryParameter(entity.getKey(), entity.getValue());
            }

            authorizedUrlBuilder.scheme(request.url().scheme());
            authorizedUrlBuilder.host(request.url().host());
            request = request.newBuilder()
                    .method(request.method(), request.body())
                    .url(authorizedUrlBuilder.build())
                    .build();

        }


        Response response = chain.proceed(request);

        ResponseBody responseBody = response.body();
        if (responseBody != null) {
            long contentLength = responseBody.contentLength();
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();

            if ("gzip".equals(response.headers().get("Content-Encoding"))) {
                GzipSource gzippedResponseBody = new GzipSource(buffer.clone());
                buffer = new Buffer();
                buffer.writeAll(gzippedResponseBody);
            }

            MediaType contentType = responseBody.contentType();
            Charset charset;
            if (contentType == null || contentType.charset(StandardCharsets.UTF_8) == null) {
                charset = StandardCharsets.UTF_8;
            } else {
                charset = contentType.charset(StandardCharsets.UTF_8);
            }

            if (charset != null && contentLength != 0L) {
                return intercept(response, request.newBuilder().build().url().toString(), buffer.clone().readString(charset));
            }
        }

        return chain.proceed(request);
    }


    abstract Response intercept(Response response, String url, String body) throws IOException;
}
